package com.zwq.springbootlearn.handler;

import com.zwq.springbootlearn.exception.GirlException;
import com.zwq.springbootlearn.model.Result;
import com.zwq.springbootlearn.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: zwq
 * Create in 2018/6/30 17:36
 */
//统一异常处理，拦截Controller抛出的异常并进行处理
@ControllerAdvice
public class MyExceptionHandler {
    private final static Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);

    //统一异常处理，拦截所有异常
    @ExceptionHandler(value = Exception.class)
    @ResponseBody //将异常信息返回给请求者
    public Result handler(Exception e){
        //自定义异常
        if(e instanceof GirlException){
            GirlException girlException = (GirlException)e;
            return ResultUtil.error(girlException.getCode(),girlException.getMessage());
        }else{
            //其他异常
            logger.error("系统异常：{}",e);
            return ResultUtil.error(-1,"未知错误");
        }
    }
}
